package com.bxd.baodan.activity;

import android.graphics.Color;
import android.text.SpannableString;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.item.GanHuoBean;
import com.bxd.baodan.item.ProductItem;
import com.bxd.baodan.item.ThinkWordBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.KeyWordUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SortUtil;
import com.bxd.baodan.util.SpKey;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.SearchView;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/15.
 */

public class SearchProduceActivity extends BaseListActivity<ProductItem> {
    private SearchView searchView;
    private TextView count_dec;
    private String key;


    private LinearLayout historyLy;
    private TagFlowLayout historyTagLayout;
    private LinearLayout searchThinkLy;
    private ListView searchThinkLv;
    private ImageView historyDelIv;
    private TextView searchThinkTv;
    private LinearLayout searchDataLy;


    private CommonAdapter<ThinkWordBean.ThinkWordItem> thinkWordIAdapter;
    List<ThinkWordBean.ThinkWordItem> thinkList = new ArrayList<>();
    private CommonAdapter<GanHuoBean> artileAdapter;
    private List<GanHuoBean> articleList = new ArrayList<>();


    private List<String> historyList = new ArrayList<>();
    TagAdapter<String> historyAdapter;

    public final static String HISTORY = "history";
    public final static String THINK = "think";
    public final static String JOIN = "join";

    private String hintStr = "";

    private boolean searchHint;
    private boolean isSearching;


    @Override
    protected int getActivityLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void preDone() {
        setSearchBar();
        initView();
        setAdapter();
        getHotWord();



        key = getIntent().getStringExtra("key");
        searchView = findViewById(R.id.search_view);
        count_dec = findViewById(R.id.count_dec);


        searchView.setSearchViewListener(new SearchView.SearchViewListener() {
            @Override
            public void textChanged(String text) {

                if (isSearching) {
                    isSearching = false;
                } else {
                    key = text;
                    getThinkWordData();
                    showViewVisible(THINK);
                }

            }

            @Override
            public void onSearch(String text, int cate_id) {


                if (text.isEmpty() && !hintStr.isEmpty()) {
                    text = hintStr;
                    searchHint = true;
                }
                if (text.isEmpty()) {
                    return;
                }

                historyList.add(text);

                SortUtil.removeDuplicateWithOrder(historyList);
                String historyData = GsonUtil.toJson(historyList);
                SpUtil.getInstance().savaString(SpKey.SEARCH_HISTORY, historyData);

                showViewVisible(JOIN);
                key = text;
                netUtil.setParams("keyword", key);
                isSearching = true;
                autoRefresh();



            }

            @Override
            public void onEmpty() {
                if (searchHint) {
                    searchHint = false;
                } else {
                    key = "";
                    getHistoryData();

                }
                isSearching = false;

            }
        });
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchView.et.setText(key);
        if (!StringUtil.isEmpty(key)) {
            showViewVisible(JOIN);
            autoRefresh();
        }


    }


    private void initView() {
        searchView = findViewById(R.id.search_view);
        searchView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);


        searchDataLy = findViewById(R.id.search_data_ly);

        historyLy = (LinearLayout) findViewById(R.id.history_ly);
        historyDelIv = (ImageView) findViewById(R.id.history_del_iv);
        historyTagLayout = (TagFlowLayout) findViewById(R.id.id_flowlayout);
        searchThinkLy = (LinearLayout) findViewById(R.id.search_think_ly);
        searchThinkLv = (ListView) findViewById(R.id.search_think_lv);
        searchThinkTv = (TextView) findViewById(R.id.search_think_tv);

        searchView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchProduceActivity.this.finish();
            }
        });

        historyDelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpUtil.getInstance().savaString(SpKey.SEARCH_HISTORY, "");
                getHistoryData();
            }
        });


    }

    private void getHistoryData() {
        showViewVisible(HISTORY);
        String history = SpUtil.getInstance().getString(SpKey.SEARCH_HISTORY);
        historyList.clear();
        if (StringUtil.isEmpty(history)) {
            historyLy.setVisibility(View.GONE);
            historyAdapter.notifyDataChanged();
            return;
        }
        List<String> his = GsonUtil.fromJsonList(history, String.class);
        historyList.addAll(his);
        historyLy.setVisibility(View.VISIBLE);
        historyAdapter.notifyDataChanged();

    }

    private void getThinkWordData() {
        NetUtil netUtil = new NetUtil(SearchProduceActivity.this, JsonApi.COMMON_KEYWORDSEARCH);
        LogUtil.e("thinkey: " + key);
        netUtil.setParams("keyword", key);
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                ThinkWordBean bean = (ThinkWordBean) GsonUtil.fromJson(data, ThinkWordBean.class);

                List<ThinkWordBean.ThinkWordItem> list = bean.list;
                thinkList.clear();
                if (list != null) {
                    if (list.size() > 5) {
                        for (int i = 0; i < 5; i++) {
                            thinkList.add(list.get(i));
                        }
                    } else {
                        thinkList.addAll(list);
                    }

                }

                thinkWordIAdapter.notifyDataSetChanged();
            }
        });

    }

    private void showViewVisible(String str) {
        historyLy.setVisibility(View.GONE);
        searchThinkLy.setVisibility(View.GONE);
        searchDataLy.setVisibility(View.GONE);

        switch (str) {
            case JOIN:
                searchDataLy.setVisibility(View.VISIBLE);
                break;
            case THINK:
                searchThinkLy.setVisibility(View.VISIBLE);
                searchThinkTv.setText("查看【" + key + "】的搜索结果");
                searchThinkTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setKeyAndSearch(key);
                    }
                });
                break;
            case HISTORY:
                historyLy.setVisibility(View.VISIBLE);
                break;
        }

    }

    private void setKeyAndSearch(String str) {
        key = str;
        searchView.et.setText(str);
        searchView.search(key);

    }

    private void setAdapter() {

        thinkWordIAdapter = new CommonAdapter<ThinkWordBean.ThinkWordItem>(this, thinkList, R.layout.layout_think_word) {
            @Override
            public void convert(ViewHolder holder, final ThinkWordBean.ThinkWordItem item) {

                if (holder.getPosition() < 5) {
                    holder.getView(R.id.main).setVisibility(View.VISIBLE);
                    TextView tv = holder.getView(R.id.tv);
                    SpannableString spannableString = KeyWordUtil.matcherSearchTitle(Color.parseColor("#999999"), item.qk_name, key);
                    tv.setText(spannableString);
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            setKeyAndSearch(item.qk_name);


                            thinkList.clear();
                            thinkWordIAdapter.notifyDataSetChanged();
                            searchThinkLy.setVisibility(View.GONE);
                        }
                    });
                }else {
                    holder.getView(R.id.main).setVisibility(View.GONE);
                }

            }
        };

        historyAdapter = new TagAdapter<String>(historyList) {
            @Override
            public View getView(FlowLayout parent, int position, final String str) {
                final TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv_1, historyTagLayout, false);
                tv.setText(str);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setKeyAndSearch(str);
                        historyLy.setVisibility(View.GONE);
                        searchDataLy.setVisibility(View.VISIBLE);
                        searchThinkLy.setVisibility(View.GONE);
                    }
                });
                return tv;
            }
        };


        historyTagLayout.setAdapter(historyAdapter);
        searchThinkLv.setAdapter(thinkWordIAdapter);


    }


    public void getHotWord() {
        NetUtil netUtil = new NetUtil(this, JsonApi.THINK_WORD);
        netUtil.setParams("inputPos","product");
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                String key = JSONUtil.getData("keyword", data);
                searchView.et.setHint(key);
                hintStr = key;

            }
        });
    }


    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<ProductItem>>() {
        }.getType();
    }


    @Override
    public int getItemLayout() {
        return R.layout.product_item_new;
    }

    @Override
    public void convert(ViewHolder holder, final ProductItem item) {
        holder.setText(R.id.p_name, item.p_name);
        holder.setText(R.id.p_features, item.p_features);
        if (StringUtil.isEmpty(item.cat_name)) {
            holder.getView(R.id.cat_name).setVisibility(View.GONE);
        } else {
            holder.setText(R.id.cat_name, item.cat_name);
        }

        if (StringUtil.isEmpty(item.price)) {
            holder.getView(R.id.p_price).setVisibility(View.GONE);
            holder.getView(R.id.explain).setVisibility(View.GONE);

        } else {
            holder.setText(R.id.p_price, item.price);
            holder.getView(R.id.p_price).setVisibility(View.VISIBLE);
            holder.getView(R.id.explain).setVisibility(View.VISIBLE);
        }

        GlideUtil.loadImage(SearchProduceActivity.this, item.p_img, (ImageView) holder.getView(R.id.p_image));


        holder.getView(R.id.p_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //item.p_url= "https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST171047535012&productCode=PRD160436305017&promoteCategory=single_product&token=";
                MobclickAgent.onEvent(App.getContext(), "");

                openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{item.p_url});
            }
        });

    }

    @Override
    protected String getArrayStr(String json_data) {
        String count = JSONUtil.getData("count", json_data);
        String countStr = "共搜到" + count + "条 “" + key + "” 相关信息";

        final SpannableString keyDec = KeyWordUtil.matcherSearchTitle(Color.parseColor("#16c571"), countStr, key);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                count_dec.setText(keyDec);
            }
        });


        return JSONUtil.getArrayData("list", json_data);
    }

    @Override
    public void setNetUtil() {

        netUtil = new NetUtil(this, JsonApi.PRODUCT_SEARCH);
        netUtil.setParams("keyword", key);
    }

}
